package edu.sctu.xialei.june.day20150615one;

import java.io.*;
import java.nio.Buffer;
import java.util.Scanner;

/**
 * Created by Administrator on 2015/6/15.
 */

/*inputStream and outputStream

 */
public class IOUtil {
    private File file;
    private String rootDir = "f://xialei_IO_File_tests//";
    private Scanner input = new Scanner(System.in);
    FileInputStream fileInputStream;

    //    input the path of file or Folder
    private File setPath() {
        String path = input.next();
        file = new File(rootDir + path);

        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return file;
    }


    //    print the file json_data by Char
    public void printerByChar() {
        setPath();

        try {
            int value;

            while ((value = fileInputStream.read()) != -1) {
                System.out.println((char) value);
            }
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    print the File json_data by char array
    public void printerByArray() {
        setPath();

        char[] values = new char[100];
        int value;
        int count = 0;

        try {
            while ((value = fileInputStream.read()) != -1) {
                values[count] = (char) value;
                count++;
            }
            fileInputStream.close();
            System.out.println(values);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    copy the file with fileInputStream and fileOutputStream
    public void copyFile() {
        setPath();

        File fileWrite = new File(rootDir + input.next());

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileWrite);
            int value;
            while ((value = fileInputStream.read()) != -1) {
                fileOutputStream.write(value);
            }
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //   create a file and write in this program
    public void createFileAndWrite() {
        File fileByWrite = new File(rootDir + input.next());

        String value = input.next();

        try {
            FileWriter fileWrite = new FileWriter(fileByWrite);

            for (int start = 0,end = 5; (end*5) < value.length();) {

                fileWrite.write(value,start,end);
            }

            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

